"""
抽象接口定义 - 确保模块间低耦合
定义各层的标准接口，支持不同实现的无缝替换
"""

from abc import ABC, abstractmethod
from typing import List, Dict, Any, Optional, Union, AsyncGenerator
from dataclasses import dataclass
from enum import Enum
import asyncio


# ================================
# 数据模型定义
# ================================

@dataclass
class Document:
    """文档模型"""
    id: str
    content: str
    metadata: Dict[str, Any]
    embedding: Optional[List[float]] = None
    

@dataclass
class SearchResult:
    """搜索结果模型"""
    document: Document
    score: float
    relevance_type: str  # vector, keyword, graph


@dataclass 
class Entity:
    """图谱实体模型"""
    id: str
    type: str  # person, company, skill, etc.
    properties: Dict[str, Any]


@dataclass
class Relationship:
    """图谱关系模型"""
    source: str
    target: str
    type: str  # works_at, has_skill, etc.
    properties: Dict[str, Any]


@dataclass
class AgentMessage:
    """智能体消息模型"""
    content: str
    sender: str
    message_type: str  # task, result, question
    metadata: Dict[str, Any] = None


class TaskStatus(Enum):
    """任务状态"""
    PENDING = "pending"
    IN_PROGRESS = "in_progress" 
    COMPLETED = "completed"
    FAILED = "failed"


@dataclass
class Task:
    """任务模型"""
    id: str
    description: str
    task_type: str
    status: TaskStatus = TaskStatus.PENDING
    result: Optional[Any] = None
    metadata: Dict[str, Any] = None


# ================================
# 数据层接口
# ================================

class VectorStoreInterface(ABC):
    """向量存储抽象接口"""
    
    @abstractmethod
    async def add_documents(self, documents: List[Document]) -> bool:
        """添加文档"""
    
    @abstractmethod 
    async def search_similar(
        self, 
        query_embedding: List[float], 
        top_k: int = 10,
        filter_metadata: Optional[Dict[str, Any]] = None
    ) -> List[SearchResult]:
        """向量相似度搜索"""
    
    @abstractmethod
    async def update_document(self, doc_id: str, document: Document) -> bool:
        """更新文档"""
    
    @abstractmethod
    async def delete_document(self, doc_id: str) -> bool:
        """删除文档"""


class GraphStoreInterface(ABC):
    """图谱存储抽象接口"""
    
    @abstractmethod
    async def add_entity(self, entity: Entity) -> bool:
        """添加实体"""
    
    @abstractmethod
    async def add_relationship(self, relationship: Relationship) -> bool:
        """添加关系"""
    
    @abstractmethod
    async def find_related_entities(
        self, 
        entity_id: str, 
        relation_types: Optional[List[str]] = None,
        max_depth: int = 2
    ) -> List[Entity]:
        """查找相关实体"""
    
    @abstractmethod
    async def query_graph(self, cypher_query: str) -> List[Dict[str, Any]]:
        """执行图查询"""


class DocumentStoreInterface(ABC):
    """文档存储抽象接口"""
    
    @abstractmethod
    async def store_document(self, doc_id: str, content: bytes, metadata: Dict[str, Any]) -> str:
        """存储文档"""
    
    @abstractmethod
    async def retrieve_document(self, doc_id: str) -> Optional[bytes]:
        """检索文档"""
    
    @abstractmethod
    async def list_documents(self, filter_metadata: Optional[Dict[str, Any]] = None) -> List[str]:
        """列出文档"""


# ================================
# LightRAG引擎层接口  
# ================================

class IngestionInterface(ABC):
    """数据灌入接口"""
    
    @abstractmethod
    async def process_document(self, document: Document) -> Document:
        """处理单个文档"""
    
    @abstractmethod
    async def batch_process_documents(self, documents: List[Document]) -> List[Document]:
        """批量处理文档"""


class RetrievalInterface(ABC):
    """检索接口"""
    
    @abstractmethod
    async def retrieve(
        self, 
        query: str, 
        top_k: int = 10,
        retrieval_modes: List[str] = ["vector", "keyword", "graph"]
    ) -> List[SearchResult]:
        """混合检索"""


class RerankingInterface(ABC):
    """重排接口"""
    
    @abstractmethod
    async def rerank(
        self, 
        query: str, 
        results: List[SearchResult], 
        top_k: int = 5
    ) -> List[SearchResult]:
        """重新排序搜索结果"""


class GenerationInterface(ABC):
    """生成接口"""
    
    @abstractmethod
    async def generate(
        self, 
        query: str, 
        context: List[SearchResult],
        template: Optional[str] = None
    ) -> str:
        """生成回答"""


# ================================
# 智能体层接口
# ================================

class AgentInterface(ABC):
    """智能体抽象接口"""
    
    @property
    @abstractmethod
    def name(self) -> str:
        """智能体名称"""
    
    @property
    @abstractmethod
    def capabilities(self) -> List[str]:
        """智能体能力列表"""
    
    @abstractmethod
    async def process_task(self, task: Task) -> Task:
        """处理任务"""
    
    @abstractmethod
    async def can_handle_task(self, task: Task) -> bool:
        """判断是否能处理该任务"""


class ToolInterface(ABC):
    """工具抽象接口"""
    
    @property
    @abstractmethod 
    def name(self) -> str:
        """工具名称"""
    
    @abstractmethod
    async def execute(self, **kwargs) -> Any:
        """执行工具"""


class OrchestratorInterface(ABC):
    """编排器接口"""
    
    @abstractmethod
    async def orchestrate_task(self, task: Task) -> Task:
        """编排任务执行"""
    
    @abstractmethod
    def register_agent(self, agent: AgentInterface):
        """注册智能体"""
    
    @abstractmethod
    def register_tool(self, tool: ToolInterface):
        """注册工具"""


# ================================
# 服务层接口
# ================================

class WorkflowInterface(ABC):
    """工作流接口"""
    
    @abstractmethod
    async def execute_workflow(
        self, 
        workflow_name: str, 
        input_data: Dict[str, Any]
    ) -> Dict[str, Any]:
        """执行工作流"""


class CacheInterface(ABC):
    """缓存接口"""
    
    @abstractmethod
    async def get(self, key: str) -> Optional[Any]:
        """获取缓存"""
    
    @abstractmethod
    async def set(self, key: str, value: Any, ttl: Optional[int] = None) -> bool:
        """设置缓存"""
    
    @abstractmethod
    async def delete(self, key: str) -> bool:
        """删除缓存"""


# ================================
# 事件系统接口
# ================================

class EventInterface(ABC):
    """事件接口"""
    
    @abstractmethod
    async def publish(self, event_type: str, data: Dict[str, Any]):
        """发布事件"""
    
    @abstractmethod
    async def subscribe(self, event_type: str, callback):
        """订阅事件"""


# ================================
# 插件系统接口
# ================================

class PluginInterface(ABC):
    """插件接口"""
    
    @property
    @abstractmethod
    def name(self) -> str:
        """插件名称"""
    
    @property
    @abstractmethod
    def version(self) -> str:
        """插件版本"""
    
    @abstractmethod
    async def initialize(self, config: Dict[str, Any]):
        """初始化插件"""
    
    @abstractmethod
    async def cleanup(self):
        """清理资源"""